package com.leyou.item.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


@Service
public class BrandServiceimpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;
    @Override
    public PageResult<Brand> page(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        PageHelper.startPage(page,rows);
        Example example = new Example(Brand.class);
        if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+(desc? " DESC" : " ASC"));
        }
        if(StringUtils.isNotBlank(key)){
            //Example.Criteria criteria = example.createCriteria();
            example.createCriteria().andLike("name","%"+key+"%");

        }
        Page<Brand> brandPage= (Page<Brand>) brandMapper.selectByExample(example);
        return new  PageResult<>(brandPage.getTotal(),new Long(brandPage.getPages()),brandPage);

    }
    @Transactional
    @Override
    public void addBrand(Brand brand, List<Long> cids) {
        brandMapper.insertSelective(brand);
        cids.forEach(cid->{
            this.brandMapper.insertCategoryBrand(cid, brand.getId());

        });


    }

    @Override
    public Brand queryBrandById(Long brandId) {

        return this.brandMapper.selectByPrimaryKey(brandId);
    }

    @Override
    public List<Brand> queryBrandByCategory(Long cid) {
        return this.brandMapper.queryBrandByCategory(cid);
    }
}
